<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/21/24
 * Time: 1:53 PM
 */

namespace App\Http\Middleware;

use Auth;
use Closure;
use App\Models\Admin;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class VerifyAdminToken extends BaseMiddleware
{

    /**
     * 授权验证
     *
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Illuminate\Http\Response|mixed
     */
    public function handle($request, Closure $next)
    {
        // 检查此次请求中是否带有 token，如果没有则抛出异常
        try {
            $this->checkForToken($request);
        } catch (\Exception $e) {

            return response(['code' => 401, 'message' => 'token不存在', 'data' => []]);
        }
        $guard = Admin::setGuard();
        try {
            // 检测用户的登录状态，如果正常则通过
            $id = $guard->getPayload()->get('sub');

            if ($guard->byId($id)) {
                $admin = $guard->user();
                if (!$admin->status) {

                    return response(['code' => 401, 'message' => '账号未启用，请联系系统管理员', 'data' => []]);
                }
                $request['admin'] = $admin;

                return $next($request);
            }

            return response(['code' => 401, 'message' => '请先登录', 'data' => []]);
        } catch (\Exception $e) {
            // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常，刷新该用户的 token 并将它添加到响应头中
            return response(['code' => 401, 'message' => $e->getMessage(), 'data' => []]);
        }
    }
}
